package com.jumi.microservice.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.interfaces.Compare;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jm.member.common.api.volidator.WrapperAnnon;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class WrapperUtil<T>  {


    public static QueryWrapper getWrapper(QueryWrapper wrapper,Object o){
        Field[] declaredFields = ReflectUtil.getFields(o.getClass());
        if(ObjectUtil.isNull(wrapper)){
            wrapper=new QueryWrapper();
        }
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            Object o1 = null;
            try {
                o1 = declaredField.get(o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            String name = declaredField.getName();
            if(ObjectUtil.isNotEmpty(o1)){
                if(declaredField.getAnnotation(WrapperAnnon.class)!=null){
                    WrapperAnnon annotation = declaredField.getAnnotation(WrapperAnnon.class);
                    if(!annotation.flag()){ continue;}
                    String queryColumn = annotation.queryColumn();
                    String queryType = annotation.queryType();
                    Method methodByName = ReflectUtil.getMethod(Compare.class,queryType,Object.class,Object.class);
                    try {
                        try {
                            methodByName.invoke(wrapper,queryColumn,o1);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }else{
                    wrapper.eq(StrUtil.toUnderlineCase(name),o1);
                }

            }
        }
        return wrapper;
    }


    public static void setTimeQueryWrapper(QueryWrapper wrapper, LocalDateTime beginTime, LocalDateTime endTime){
        if(ObjectUtil.isNotEmpty(beginTime)) {
            wrapper.ge("create_time",beginTime);
        };
        if(ObjectUtil.isNotEmpty(endTime)){
            wrapper.lt("create_time",endTime);
        }
    }

    public static void setTimeQueryWrapper(QueryWrapper wrapper, LocalDateTime beginTime, LocalDateTime endTime,String col){
        if(ObjectUtil.isNotEmpty(beginTime)) {
            wrapper.ge(col,beginTime);
        };
        if(ObjectUtil.isNotEmpty(endTime)){
            wrapper.lt(col,endTime);
        }
    }

}
